package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Autowired
    private MapApi mapApi;
    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }
    /**
     * 查询用户默认地址
     * @return
     */
    @Override
    public AddressBookResDTO findDefaultAddress() {
        //用户id  默认地址
        //select * from address_book where user_id = 登录用户 and is_default = 1
        System.out.println(UserContext.currentUserId());
        AddressBook addressBook = this.lambdaQuery()
                .eq(AddressBook::getUserId, UserContext.currentUserId())//登录用户id
                .eq(AddressBook::getIsDefault, 1)//默认地址
                .one();
        if (ObjectUtil.isNull(addressBook)){
            return null;
        }
        //转换
        return BeanUtil.copyProperties(addressBook,AddressBookResDTO.class);
    }

    /**
     * 新增地址
     * @param addressBookUpsertReqDTO
     */
    @Override
    public void saveAddress(AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        //得到用户的id
        Long id = UserContext.currentUserId();

        //该地址是否为默认地址
        if (addressBookUpsertReqDTO.getIsDefault() == 1){
            this.lambdaUpdate()
                    .eq(AddressBook::getUserId,id)
                    .set(AddressBook::getIsDefault,0)
                    .update();
        }

        //转换对象
        AddressBook addressBook = BeanUtil.copyProperties(addressBookUpsertReqDTO, AddressBook.class);
        addressBook.setUserId(id);

        //判断是否传入经纬度
        if (ObjectUtil.isEmpty(addressBookUpsertReqDTO.getLocation())){
            //拼接详细地址
            String address= addressBookUpsertReqDTO.getProvince()+addressBookUpsertReqDTO.getCity()
                    +addressBookUpsertReqDTO.getCounty()+addressBookUpsertReqDTO.getAddress();
            //调用接口将详细坐标转为经纬度
            LocationResDTO dto = mapApi.getLocationByAddress(address);
            addressBookUpsertReqDTO.setLocation(dto.getLocation());
        }
        //将addressBookUpsertReqDTO中的location转化为经纬度封装到对象中
        //经度
        addressBook.setLon(NumberUtils.parseDouble(addressBookUpsertReqDTO.getLocation().split(",")[0]));
        //维度
        addressBook.setLat(NumberUtils.parseDouble(addressBookUpsertReqDTO.getLocation().split(",")[1]));
        //执行插入
        baseMapper.insert(addressBook);
    }
    /**
     * 地址分页查询
     * @param addressBookUpsertReqDTO
     * @return
     */
    @Override
    public PageResult<AddressBookResDTO> findByPage(AddressBookPageQueryReqDTO addressBookUpsertReqDTO) {
        //1.构建page对象,传入参数:1.查询对象 2.查询对象对应的实体表
        Page<AddressBook> page = PageUtils.parsePageQuery(addressBookUpsertReqDTO, AddressBook.class);
        //2.调用查询方法,传入参数:1.page对象 2.查询条件封装器
        Page<AddressBook> bookPage = baseMapper.selectPage(page, new QueryWrapper<>());
        //3.查询结果转换为PageResult
        return PageUtils.toPage(bookPage,AddressBookResDTO.class);
    }

    /**
     * 查询地址详情
     * @param id
     * @return
     */
    @Override
    public AddressBookResDTO findById(Long id) {
        AddressBook addressBook = baseMapper.selectById(id);
        return BeanUtil.copyProperties(addressBook,AddressBookResDTO.class);
    }

    /**
     * 修改地址
     * @param id,addressBookUpsertReqDTO
     */
    @Override
    public void updateAddressBook(Long id,AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        //判断传入进来的数据是否为默认地址
        if (addressBookUpsertReqDTO.getIsDefault() == 1){
            this.lambdaUpdate()
                    .eq(AddressBook::getId,UserContext.currentUserId())
                    .set(AddressBook::getIsDefault,0)
                    .update();
        }
        //转换对象
        AddressBook addressBook = BeanUtil.copyProperties(addressBookUpsertReqDTO, AddressBook.class);
        addressBook.setId(id);

        //判断传入进来的数据是否含有经纬度
        if(ObjectUtil.isEmpty(addressBookUpsertReqDTO.getLocation())){
            //组装详细的地址
            String address= addressBookUpsertReqDTO.getProvince()+addressBookUpsertReqDTO.getCity()
                    +addressBookUpsertReqDTO.getCounty()+addressBookUpsertReqDTO.getAddress();
            //调用接口
            LocationResDTO dto = mapApi.getLocationByAddress(address);
            //获得经纬度
            String location = dto.getLocation();
            addressBookUpsertReqDTO.setLocation(location);
            //复制经纬度
            if (ObjectUtil.isNotEmpty(addressBookUpsertReqDTO.getLocation())){
                //经度
                addressBook.setLon(NumberUtils.parseDouble(addressBookUpsertReqDTO.getLocation().split(",")[0]));
                //维度
                addressBook.setLat(NumberUtils.parseDouble(addressBookUpsertReqDTO.getLocation().split(",")[1]));
            }
            //执行更改
            baseMapper.updateById(addressBook);
        }
    }

    /**
     * 修改是否为默认地址
     * @param id
     * @param flag
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDefaultStatus(Long id, Integer flag) {
        //如果设默认地址，先把其他地址取消默认
        if (1 == flag) {
            this.lambdaUpdate().set(AddressBook::getIsDefault, 0)
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .update();
        }

        //2. 修改
        AddressBook addressBook = new AddressBook();
        addressBook.setId(id);
        addressBook.setIsDefault(flag);
        getBaseMapper().updateById(addressBook);
    }
}
